package xin.nick.roc.consumer.job;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import xin.nick.roc.consumer.client.ProviderInfo;
import xin.nick.roc.consumer.client.ZkRegister;

import java.util.List;
import java.util.Map;

/**
 * @author Nick
 * @date 2021/7/11
 * @description
 */
@Slf4j
@Component
public class ProviderPongJob {



    @Scheduled(cron = "0/5 * * * * ?")
    public void execute() throws Exception {

        String path = "/provider";
        // 定时从zk获取,更新提供者的状态信息
        CuratorFramework client = ZkRegister.getClient();
        if(client == null) {
            return;
        }
        // 遍历所有的提供者
        List<String> providerList = client.getChildren().forPath(path);

        // 遍历所有提供者的响应信息
        Map<String, Long> responseTimeMap = ProviderInfo.getResponseTimeMap();

        for (String provider : providerList) {
            Long responseTime = responseTimeMap.get(provider);
            if(responseTime == null) {
                responseTime = 0L;
            }
            String timeString = new String(client.getData().forPath(path + "/" + provider));
            String[] timeArray = timeString.split(" ");
            Long lastTimestamp = Long.parseLong(timeArray[0]);
            String newTimeData = "";
            Long currentTime = System.currentTimeMillis();
            // 对于上次请求时间超过五秒的节点,进行数据清空
            if(currentTime - lastTimestamp > 5000) {
                newTimeData = new StringBuilder(String.valueOf(currentTime)).append(" 0").toString();
            } else {
                newTimeData = new StringBuilder(String.valueOf(currentTime))
                        .append(" ")
                        .append(responseTime)
                        .toString();
            }
            // 更新所有的节点信息
            client.setData().forPath(path + "/" + provider, newTimeData.getBytes());
//            responseTimeMap.put(provider, 0L);
        }
        log.info("刷新所有的provider节点信息");
    }
}
